package com.quanquan.resource.controller;

import com.alibaba.fastjson.JSONObject;
import com.quanquan.resource.configBeans.OssConfigBean;
import com.quanquan.resource.dto.IdDTO;
import com.quanquan.resource.dto.ImageDTO;
import com.quanquan.resource.entity.Image;
import com.quanquan.resource.service.ImageService;
import enums.ResCodeEnum;
import exceptions.ImgException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.Base64ToMultipartUtil;
import utils.RandomUtil;
import utils.StringUtil;
import web.response.ResultBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片管理
 */

@RestController
@RequestMapping("/image")
public class ImageController {


    public static final Logger logger = LoggerFactory.getLogger(ImageController.class);

    @Value("${storage-params.serverurl}")
    private  String serverurl;

    @Autowired
    private ImageService imageService;


    @Autowired
    private OssConfigBean configBean;


    /**
     * @param request 上传图片
     * @param file
     * @param cover
     * @param logo
     * @param sign
     * @return
     */
    @PostMapping(value = "/upload")
    public ResultBody imageUpload(HttpServletRequest request, MultipartFile file, String cover, String logo, String sign,String imgStr) {

        try {
            String fileName = RandomUtil.getRandomFileName();
            String imgUrl = serverurl+fileName;

        if(StringUtil.isNotEmpty(imgStr) && file==null){
//            String imgStrs = imgStr.replaceAll("data:image/png;base64,", "");

            MultipartFile multipartFile = Base64ToMultipartUtil.base64ToMultipart(imgStr);
            multipartFile.transferTo(new File(imgUrl));
        }else{

            file.transferTo(new File(imgUrl));
        }

            Map<String, String> map = new HashMap<>();


            //保存图片信息
            Image image = imageService.createImage(cover, logo, sign, imgUrl);

            map.put("id", image.getId());
            map.put("imageAddress", image.getImageAddress());
           return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg(),map);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());
        }


    }

//
//    @PostMapping("/upload_base64")
//    public ResultBody  imageUpload(String imgStr,String cover, String logo, String sign){
//        String fileName = RandomUtil.getRandomFileName();
//        String imgUrl = serverurl+fileName;
//         ImageUtil.generateImage(imgStr, imgUrl);
//        //保存图片信息
//        Image image = imageService.createImage(cover, logo, sign, imgUrl);
//        if(image == null){
//            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg(),"上传图片失败");
//        }
//        Map<String, String> map = new HashMap<>();
//        map.put("id", image.getId());
//        map.put("imageAddress", image.getImageAddress());
//        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg(),map);
//
//    }


    /**
     * 删除图片
     *
     * @param imageId
     */
    @GetMapping("/image_remove")
    public ResultBody removeImage(String imageId) {
        String msg = null;
        try {
            msg = imageService.removeImage(imageId);
        } catch (ImgException e) {
            e.printStackTrace();
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "成功", JSONObject.toJSON(msg));
    }

    /**
     * 根据图片ID查询单张图片
     */
    @PostMapping("/image_edit")
    public ResultBody findImageById(String imageId) {
        Image image = imageService.getImage(imageId);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "成功", JSONObject.toJSON(image));
    }

    /**
     * 根据图片ID查询单张图片（外部模块使用）
     */
    @PostMapping("/image_edit_out")
    @ResponseBody
    public ImageDTO findImageByIdOut(@RequestBody IdDTO idDTO) {
        String imageId = idDTO.getForeignKeyId();
        List<Image> images = new ArrayList<>();
        ImageDTO imageDTO = new ImageDTO();
        Image image = imageService.getImage(imageId);
        images.add(image);
        imageDTO.setImageDTOs(images);
        return imageDTO;
    }


    /**
     * 根据外键查询图片
     */
    @PostMapping("/image_query")
    @ResponseBody
    public ImageDTO fingImagesByForeignKeyId(@RequestBody IdDTO idDTO) {
        String foreignKeyId = idDTO.getForeignKeyId();
        ImageDTO images = new ImageDTO();
        try {
            List<Image> images1 = imageService.findImages(foreignKeyId);

            images.setImageDTOs(images1);
        } catch (ImgException e) {
            e.printStackTrace();
        }
        return images;

    }


    /**
     * 根据多个id查询图片
     *
     * @param idDTO
     * @return
     */
    @PostMapping("/getImages")
    @ResponseBody
    public ImageDTO fingImageByIds(@RequestBody IdDTO idDTO) {
        ImageDTO imageDTO = new ImageDTO();
        List<String> imageIds = idDTO.getImageIds();
        List<Image> images = imageService.queryImagesById(imageIds);
        imageDTO.setImageDTOs(images);
        return imageDTO;

    }


    /**
     * 后台查询或修改会员权益
     * @return
     */
    @PostMapping("/right_and_interests")
    public ResultBody rightsAndInterests (@RequestBody Image image){
        //绑定权益关系图片
        String msg = imageService.bindRightAndInterests(image.getId());
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "成功", JSONObject.toJSON(msg));
    }

    @PostMapping("/query_right_and_interests")
    public ResultBody findRightAndInterests (){
    //根据类型查询图片
        Image image = null;
        try {
            image = imageService.queryRightAndInterests();
        } catch (ImgException e) {
            e.printStackTrace();
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "成功", JSONObject.toJSON(image));
    }
}
